﻿create PROCEDURE Sync.SP_VacationYears_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @VacationYears_Temp TABLE 
		(
			VacationYearID UniqueIdentifier,
			[VacationYear] nvarchar(50),
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @VacationYears_Temp 
	   SELECT	Tbl.Col.value('VacationYearID[1]','uniqueidentifier') VacationYearID,
                Tbl.Col.value('VacationYear[1]', 'nvarchar(50)') [VacationYear],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/VacationYears') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[VacationYears] ([VacationYearID],[VacationYear])
	SELECT t.[VacationYearID],t.[VacationYear]
	FROM  @VacationYears_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.VacationYears_Tracking s
        WHERE t.VacationYearID = s.VacationYearID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[VacationYears]
	SET [VacationYears].[VacationYear] = t.[VacationYear] 
	FROM [dbo].[VacationYears] s JOIN @VacationYears_Temp t 
    ON t.VacationYearID = s.VacationYearID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.VacationYears_Tracking r
				  WHERE t.VacationYearID = r.VacationYearID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[VacationYears]
    FROM @VacationYears_Temp t JOIN [dbo].[VacationYears] s
    ON t.VacationYearID = s.VacationYearID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END














